//
//  FilterViewController.m
//  quxiangtao
//
//  Created by xbmios on 2018/8/6.
//  Copyright © 2018年 shanhaijin. All rights reserved.
//

#import "FilterViewController.h"
#import "ZYSideSlipFilterRegionModel.h"
#import "SideSlipBaseTableViewCell.h"
#import "CommonItemModel.h"
#import "JTNavigationController.h"

#define SLIP_ORIGIN_FRAME CGRectMake(SCREEN_WIDTH, 0, WIDTH - _sideSlipLeading, HEIGHT)
#define SLIP_DISTINATION_FRAME CGRectMake(_sideSlipLeading, 0, WIDTH - _sideSlipLeading, HEIGHT)

#define BOTTOM_BUTTON_HEIGHT jisuan(160)
#define SlipWidth (WIDTH - jisuan(670))
const CGFloat ANIMATION_DURATION_DEFAULT = 0.3f;
//const CGFloat SIDE_SLIP_LEADING_DEFAULT = SlipWidth;

id (*objc_msgSendGetCellIdentifier)(id self, SEL _cmd) = (void *)objc_msgSend;
CGFloat (*objc_msgSendGetCellHeight)(id self, SEL _cmd) = (void *)objc_msgSend;
id (*objc_msgSendCreateCellWithIndexPath)(id self, SEL _cmd, NSIndexPath *) = (void *)objc_msgSend;


static NSString *commonTableViewCellID = @"commonTableViewCellID";
static NSString *priceTableViewCellID = @"priceTableViewCellID";

@interface FilterViewController ()<UITableViewDelegate, UITableViewDataSource, SideSlipBaseTableViewCellDelegate>

@property (copy, nonatomic) SideSlipFilterCommitBlock commitBlock;
@property (copy, nonatomic) SideSlipFilterResetBlock resetBlock;

@property (copy, nonatomic) FilterViewDimissBlock dimissBlock;

@property (strong, nonatomic) UITableView *mainTableView;
@property (strong, nonatomic) UIView *backCover;
@property (weak, nonatomic) UIViewController *sponsor;

@property (assign, nonatomic) CGFloat height;

@property (strong, nonatomic) NSMutableDictionary *templateCellDict;

//@property (assign, nonatomic) NSInteger number;

@end

@implementation FilterViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
}

- (instancetype)initWithSponsor:(UIViewController *)sponsor withCommitBlock:(CommitBlock)dataCommitBlock withViewDimissBlock:(FilterViewDimissBlock)dimissBlock{

    FilterViewController *filterVC = [[FilterViewController alloc] initWithSponsor:sponsor resetBlock:^(NSArray *dataList) {
        
        for (ZYSideSlipFilterRegionModel *model in dataList) {
            //selectedStatus
            for (CommonItemModel *itemModel in model.itemList) {
                [itemModel setSelected:NO];
            }
            //selectedItem
            model.selectedItemList = nil;
        }
        
    } commitBlock:^(NSArray *dataList) {
        
        NSMutableString *dataCommitString = [[NSMutableString alloc] init];
        
        // 服务
        ZYSideSlipFilterRegionModel *serviceRegionModel = dataList[0];
        NSMutableString *serviceInfoString = [NSMutableString stringWithString:@"\n来源:\n"];
        NSMutableArray *serviceItemSelectedArray = [NSMutableArray array];
        for (CommonItemModel *itemModel in serviceRegionModel.itemList) {
            if (itemModel.selected) {
                [serviceItemSelectedArray addObject:[NSString stringWithFormat:@"%@-%@", itemModel.itemId, itemModel.itemName]];
            }
        }
        [serviceInfoString appendString:[serviceItemSelectedArray componentsJoinedByString:@", "]];
        NSLog(@"%@", serviceInfoString);
        
        [dataCommitString appendString:serviceInfoString];
        
        // 价格
        
        
        
        // 其他
        NSMutableString *commonRegionString = [NSMutableString string];
        for (int i = 2; i < dataList.count; i ++) {
            ZYSideSlipFilterRegionModel *commonRegionModel = dataList[i];
            [commonRegionString appendFormat:@"\n%@:", commonRegionModel.regionTitle];
            NSMutableArray *commonItemSelectedArray = [NSMutableArray array];
            for (CommonItemModel *itemModel in commonRegionModel.itemList) {
                if (itemModel.selected) {
                    [commonItemSelectedArray addObject:[NSString stringWithFormat:@"%@-%@", itemModel.itemId, itemModel.itemName]];
                }
            }
            [commonRegionString appendString:[commonItemSelectedArray componentsJoinedByString:@", "]];
        
        }
        
        NSLog(@"%@", commonRegionString);
        
        
        [dataCommitString appendString:commonRegionString];
        
        
        if (dataCommitBlock) {
            
            dataCommitBlock(dataCommitString);
        }
        
    }  withViewDimissBlock:^(BOOL isDimiss) {
        
        if (dimissBlock) {
            
            dimissBlock(isDimiss);
        }
        
    }];
    
    return filterVC;
}

- (instancetype)initWithSponsor:(UIViewController *)sponsor
                     resetBlock:(SideSlipFilterResetBlock)resetBlock
                    commitBlock:(SideSlipFilterCommitBlock)commitBlock withViewDimissBlock:(FilterViewDimissBlock)dimissBlock {
   
    self = [super init];
    
    if (self) {
        
        self.automaticallyAdjustsScrollViewInsets = NO;
        
        self.height = 0.0;
        
        _sponsor = sponsor;
        _resetBlock = resetBlock;
        _commitBlock = commitBlock;
        _dimissBlock = dimissBlock;
        JTNavigationController *filterNavigation = [[JTNavigationController alloc] initWithRootViewController:self];
        [filterNavigation setNavigationBarHidden:YES];
        filterNavigation.navigationBar.translucent = NO;
        [filterNavigation.view setFrame:SLIP_ORIGIN_FRAME];
        
        self.animationDuration = .3f;
        self.sideSlipLeading = WIDTH - jisuan(670);
        
        [self configureStatic];
        [self configureUI];
        
    }
    
    return self;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerV = [[UIView alloc] init];
    headerV.backgroundColor = WhiteColor;
    
    return headerV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return jisuan(50);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZYSideSlipFilterRegionModel *model = _dataList[indexPath.row];
    Class cellClazz =  NSClassFromString(model.containerCellClass);
    if ([(id)cellClazz respondsToSelector:@selector(cellHeight)]) {
        CGFloat cellHeight = objc_msgSendGetCellHeight(cellClazz, NSSelectorFromString(@"cellHeight"));
        return cellHeight;
    }
    NSString *identifier = objc_msgSendGetCellIdentifier(cellClazz, NSSelectorFromString(@"cellReuseIdentifier"));
    SideSlipBaseTableViewCell *templateCell = [self.templateCellDict objectForKey:identifier];
    if (!templateCell) {
        templateCell = objc_msgSendCreateCellWithIndexPath(cellClazz, NSSelectorFromString(@"createCellWithIndexPath:"), indexPath);
        templateCell.delegate = self;
        [self.templateCellDict setObject:templateCell forKey:identifier];
    }
    //update
    [templateCell updateCellWithModel:&model indexPath:indexPath];

    templateCell.cellHeigthBlock = ^(CGFloat cellHeight) {
        
        self.height = cellHeight;
        
    };
    return self.height;
 
}

#pragma mark -delegate \ datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataList.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZYSideSlipFilterRegionModel *model = _dataList[indexPath.row];
    Class cellClazz =  NSClassFromString(model.containerCellClass);
    NSString *identifier = objc_msgSendGetCellIdentifier(cellClazz, NSSelectorFromString(@"cellReuseIdentifier"));
    SideSlipBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = objc_msgSendCreateCellWithIndexPath(cellClazz, NSSelectorFromString(@"createCellWithIndexPath:"), indexPath);
        cell.delegate = self;
    }
    //update
    [cell updateCellWithModel:&model indexPath:indexPath];
    
    return cell;

}


#pragma mark -baseTableViewCellDelegate
- (void)sideSlipTableViewCellNeedsReload:(NSIndexPath *)indexPath {
    [_mainTableView reloadData];
}
- (void)sideSlipTableViewCellNeedsScrollToCell:(UITableViewCell *)cell atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated {
    NSIndexPath *indexPath = [_mainTableView indexPathForRowAtPoint:cell.center];
    [_mainTableView scrollToRowAtIndexPath:indexPath atScrollPosition:scrollPosition animated:animated];
}

#pragma mark -重置
- (void)clickResetButton:(id)sender {
    
    _resetBlock(_dataList);
    [[NSNotificationCenter defaultCenter] postNotificationName:FILTER_NOTIFICATION_NAME_DID_RESET_DATA object:nil];
    
    [_mainTableView reloadData];
}
#pragma mark -提交
- (void)clickCommitButton:(id)sender {
    
    _commitBlock(_dataList);
    [[NSNotificationCenter defaultCenter] postNotificationName:FILTER_NOTIFICATION_NAME_DID_COMMIT_DATA object:nil];

}

#pragma mark -黑色背景点击
- (void)clickBackCover:(id)sender {
    
    [self dismiss];
    
}

#pragma mark -界面展示
- (void)show {

    [_sponsor.tabBarController.view addSubview:self.backCover];
    [_sponsor.tabBarController addChildViewController:self.navigationController];
    [_sponsor.tabBarController.view addSubview:self.navigationController.view];

    [_backCover setHidden:YES];

    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:_animationDuration animations:^{
        [weakSelf.navigationController.view setFrame:CGRectMake(weakSelf.sideSlipLeading, 0, WIDTH - weakSelf.sideSlipLeading, HEIGHT)];
    } completion:^(BOOL finished) {
        [weakSelf.backCover setHidden:NO];
    }];
}

#pragma mark -界面消失
- (void)dismiss {

    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:_animationDuration animations:^{
        
        [weakSelf.navigationController.view setFrame:CGRectMake(SCREEN_WIDTH, 0, WIDTH - weakSelf.sideSlipLeading, HEIGHT)];
    } completion:^(BOOL finished) {
        [weakSelf.backCover removeFromSuperview];
        [weakSelf.navigationController.view removeFromSuperview];
        [weakSelf.navigationController removeFromParentViewController];
    }];
    
    _dimissBlock(NO);
}

#pragma mark -刷新数据
- (void)reloadListData {
    
    if (_mainTableView) {
        
        [_mainTableView reloadData];
    
    }
}


- (void)configureUI {
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view addSubview:self.mainTableView];
    //bottomView
    UIView *bottomView = [self createBottomView];
    
    self.mainTableView.frame = CGRectMake(0, 0, jisuan(670), HEIGHT - jisuan(90));
    bottomView.frame = CGRectMake(0, HEIGHT - jisuan(90), jisuan(670), jisuan(90));
    
    [self.view addSubview:bottomView];
    
//    NSLog(@"%.2f==%@==%@", HEIGHT, NSStringFromCGRect(self.mainTableView.frame), NSStringFromCGRect(bottomView.frame));

}

- (void)configureStatic {
    self.animationDuration = ANIMATION_DURATION_DEFAULT;
    self.sideSlipLeading = SlipWidth;
}
- (UIView *)createBottomView {
    UIView *bottomView = [[UIView alloc] init];
    [bottomView setTranslatesAutoresizingMaskIntoConstraints:NO];
    //resetButton
    UIButton *resetButton = [[UIButton alloc] init];
    [resetButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [resetButton addTarget:self action:@selector(clickResetButton:) forControlEvents:UIControlEventTouchUpInside];
    [resetButton.titleLabel setFont:Font(30)];
    [resetButton setTitleColor:Color333333 forState:UIControlStateNormal];
    NSString *resetString = @"重置";
    [resetButton setTitle:resetString forState:UIControlStateNormal];
    [resetButton setBackgroundColor:[UIColor whiteColor]];
    [bottomView addSubview:resetButton];
    //commitButton
    UIButton *commitButton = [[UIButton alloc] init];
    [commitButton setTranslatesAutoresizingMaskIntoConstraints:NO];
    [commitButton addTarget:self action:@selector(clickCommitButton:) forControlEvents:UIControlEventTouchUpInside];
    [commitButton.titleLabel setFont:Font(30)];
    [commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSString *commitString = @"提交";
    [commitButton setTitle:commitString forState:UIControlStateNormal];
    [commitButton setBackgroundColor:Colorff0000];
    [bottomView addSubview:commitButton];
    
    resetButton.frame = CGRectMake(0, 0, jisuan(670) / 2.0, jisuan(90));
    commitButton.frame = CGRectMake(jisuan(670) / 2.0, 0, jisuan(670) / 2.0, jisuan(90));
    return bottomView;
}


- (void)setDataList:(NSArray *)dataList {
    _dataList = [dataList copy];
    if (_mainTableView) {
        [_mainTableView reloadData];
    }
}

#pragma mark -lazy

- (UITableView *)mainTableView {
    
    if (!_mainTableView) {
        
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        _mainTableView.backgroundColor = WhiteColor;
        
        _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        
        _mainTableView.estimatedRowHeight = 0;
        _mainTableView.estimatedSectionFooterHeight = 0;
        _mainTableView.estimatedSectionHeaderHeight = 0;
        
        
        _mainTableView.showsVerticalScrollIndicator = NO;
        _mainTableView.showsHorizontalScrollIndicator = NO;

        if (@available(iOS 11.0, *)) {
            
            _mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }

    }
    
    return _mainTableView;
}
- (UIView *)backCover {
   
    if (!_backCover) {
        _backCover = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [_backCover setBackgroundColor:Color333333];
        [_backCover setAlpha:0.5];
        [_backCover addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBackCover:)]];
    }
    
    return _backCover;
}

- (NSMutableDictionary *)templateCellDict {
    if (!_templateCellDict) {
        _templateCellDict = [NSMutableDictionary dictionary];
    }
    return _templateCellDict;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
